package caddy

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"strings"
)

func (cls *Caddy) SetWebsite(ctx context.Context, hostname string, reverses []*application.CaddyWebsiteReverse, tls *application.CaddyWebsiteTls) error {
	if strings.Contains(hostname, "://") {
		return errors.New("域名不允许包含协议信息")
	}

	if 0 == len(reverses) {
		return errors.New("反向代理配置表不能为空")
	}

	var website = new(application.CaddyWebsite)
	website.Tls = new(application.CaddyWebsiteTls)

	// 基础配置
	website.Hostname = hostname

	// TLS配置
	website.Tls.Enable = true
	if nil != tls {
		website.Tls = tls
	}

	// 反向代理配置
	website.Reverses = reverses

	cls.LockConfig()
	defer cls.UnlockConfig()

	var config = cls.GetConfig()
	config.Websites[hostname] = website
	cls.SetConfig(config)

	return cls.SyncToDisk(ctx, internalConfigPath)
}
